package com.furongji.education.controller.api;

import com.furongji.common.domain.vo.UserOrderVo;
import com.furongji.common.domain.vo.UserSimpleVo;
import com.furongji.common.result.Result;
import com.furongji.common.utils.GenerateCodeUtil;
import com.furongji.common.utils.MailUtil;
import com.furongji.education.domain.dto.EmailDto;
import com.furongji.education.domain.dto.UserDto;
import com.furongji.education.domain.po.User;
import com.furongji.education.service.LoginLogService;
import com.furongji.education.service.UserService;
import com.furongji.education.utils.IpUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.AllArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

@Tag(name = "前台登录管理")
@AllArgsConstructor
@RestController
@RequestMapping("/api/users")
public class UserApiController {

    private final UserService userService;

    private final LoginLogService loginLogService;

    private final RedisTemplate<String, Object> redisTemplate;

    @Operation(summary = "用户账号登录")
    @PostMapping("/login")
    public Result loginUser(@RequestBody User user, HttpServletRequest request) {
        String token = userService.login(user);
        if (token != null) {
            User userInfo = userService.getUserInfo(token);
            if (userInfo != null) {
                String ip = IpUtil.getClientIp(request);
                String userAgent = request.getHeader("User-Agent");
                loginLogService.insertLoginLog(userInfo.getId(), ip, userAgent);
            }
        }
        return Result.success(token);
    }

    @Operation(summary = "用户邮箱登录")
    @PostMapping("/emailLogin")
    public Result loginEmail(@RequestBody UserDto userDto) {
        String token = userService.loginEmail(userDto);
        return Result.success(token);
    }

    @Operation(summary = "用户注册")
    @PostMapping("/register")
    public Result registerUser(@RequestBody UserDto userDto) {
        String token = userService.register(userDto);
        return Result.success(token);
    }

    @Operation(summary = "发送验证码")
    @PostMapping("/sendCode")
    public Result sendCode(@RequestBody EmailDto emailDto) {
        String cacheKey = emailDto.getEmail();
        String code = GenerateCodeUtil.generateValidateCode(6);
        MailUtil.sendMail(emailDto.getEmail(), "云启课堂验证码：" + code + "，有效期为5分钟，请尽快输入");
        redisTemplate.opsForValue().set(cacheKey, code, 5, TimeUnit.MINUTES);
        return Result.success();
    }

    @Operation(summary = "根据token获取用户信息")
    @GetMapping("/getUserInfo")
    public Result getUserInfo(@RequestHeader("Authorization") String token) {
        User user = userService.getUserInfo(token);
        return Result.success(user);
    }

    // feign
    @Operation(summary = "根据token获取用户信息")
    @GetMapping("/getUserOrderInfo")
    public UserOrderVo getUserOrderInfo(@RequestHeader("Authorization") String token) {
        User user = userService.getUserInfo(token);
        UserOrderVo userOrderVo = new UserOrderVo(user.getId(), user.getUsername(), user.getEmail());
        return userOrderVo;
    }

    // feign 给评论微服务与文章微服务
    @Operation(summary = "根据用户Id获取用户名称与头像")
    @GetMapping("/getNameAndAvatar")
    public UserSimpleVo getNameAndAvatar(@RequestParam String userId) {
        User user = userService.getById(userId);
        UserSimpleVo userSimpleVo = new UserSimpleVo(user.getUsername(), user.getAvatar());
        return userSimpleVo;
    }
}
